package handlers

import (
	zc "ac"
	"ac-julink/cache"
	"encoding/json"
)

type JulinkRestHandler struct {
}

func NewJulinkRestHandler() *JulinkRestHandler {
	return &JulinkRestHandler{}
}

func (this *JulinkRestHandler) HandleCleanAllCaches(req *zc.ZMsg, resp *zc.ZMsg, cacheContext *cache.SyncContext) {
	cacheContext.ClearAll()
	resp.PutInt("success", 1)
	resp.SetAck()
	return
}

func (this *JulinkRestHandler) HandleCleanCaches(req *zc.ZMsg, resp *zc.ZMsg, cacheContext *cache.SyncContext) {
	wifiIdList := req.GetString("wifiIdList")

	if len(wifiIdList) > 0 {
		cacheContext.DeleteBatch(wifiIdList)
		resp.PutInt("success", 1)
		resp.SetAck()
		return
	} else {
		resp.PutInt("success", 0)
		resp.PutString("errMsg", "wifiIdList is invalid!")
		resp.SetAck()
		return
	}

}

func (this *JulinkRestHandler) HandleGetCachedValueByKey(req *zc.ZMsg, resp *zc.ZMsg, cacheContext *cache.SyncContext) {
	wifiId := req.GetString("wifiId")
	if len(wifiId) == 0 {
		resp.PutInt("success", 0)
		resp.PutString("errMsg", "can not parse wifiId from request.")
		resp.SetAck()
		return
	}
	cacheVal := cacheContext.Get(wifiId)

	if r, err := json.Marshal(cacheVal); err != nil {
		resp.PutInt("success", 0)
		resp.PutString("errMsg", err.Error())
		resp.SetAck()
		return
	} else {
		resp.PutInt("success", 1)
		resp.PutString("result", string(r))
		resp.SetAck()
		return
	}
}

func (this *JulinkRestHandler) HandleFetchAllCachedKeys(req *zc.ZMsg, resp *zc.ZMsg, cacheContext *cache.SyncContext) {
	ids := cacheContext.GetAllWifiIds()
	if a, err := json.Marshal(ids); err != nil {
		resp.PutInt("success", 0)
		resp.PutString("errMsg", err.Error())
		resp.SetAck()
		return
	} else {
		resp.PutInt("success", 1)
		resp.PutString("result", string(a))
		resp.SetAck()
		return
	}
}
